package com.keldian.mobilesafe.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;
import com.keldian.mobilesafe.dao.BlackNumberDao;

import java.lang.reflect.Method;

public class CallSmsSafeService extends Service {

    private BlackNumberDao dao;
    private MyPhoneStateListener listener;
    private InnerSmsReceiver receiver;
    private TelephonyManager tm;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    private class MyPhoneStateListener extends PhoneStateListener {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            super.onCallStateChanged(state, incomingNumber);

            switch (state) {
                //静止状态
                case TelephonyManager.CALL_STATE_IDLE:
                    System.out.println("CALL_STATE_IDLE");
                    break;
                //电话接通状态
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    System.out.println("CALL_STATE_OFFHOOK");
                    break;
                //电话铃响
                case TelephonyManager.CALL_STATE_RINGING:
                    System.out.println("CALL_STATE_RINGING");
                    //判断当前打进电话的哥们是否在仇人名单里面

                    System.out.println("incomingNumber---------" + incomingNumber);
                    //根据电话号码查询拦截的模式
                    String mode = dao.findMode(incomingNumber);
                    /**
                     * 1 电话拦截 + 短信拦截(全部拦截)
                     * 2 电话拦截
                     * 3短信拦截
                     */
                    Log.d("MyPhoneStateListener", mode);
                    if ("1".equals(mode) || "3".equals(mode)) {
                        System.out.println("你被哥拦截了--挂断电话");
//                        联系人的uri
                        Uri uri = Uri.parse("content://call_log/calls/");


//                        注册内容观察者
                        /**
                         * 第一个参数表示联系人的uri
                         * 第二个参数表示设置ture表示前缀满足即可
                         */
                        getContentResolver().registerContentObserver(uri, true,
                                new MyContentObserver(new Handler(), incomingNumber));

                        //挂断电话号码
                        endCall();

                        //系统添加通话记录的逻辑是异步执行的, 不会立即执行, 所以不能立即删除, 否则有可能删除之后,系统才添加成功
                        //所以,必须等系统添加完成后,才删除.
//                        deleteCallLog(incomingNumber);
                    }
                    break;

            }
        }

    }

    private class MyContentObserver extends ContentObserver {
        //电话号码
        private String incomingNumber;

        public MyContentObserver(Handler handler, String incomingNumber) {
            super(handler);
            this.incomingNumber = incomingNumber;
        }

        //当数据库改变的时候调用的方法
        @Override
        public void onChange(boolean selfChange) {
            // TODO Auto-generated method stub
            super.onChange(selfChange);
            deleteCallLog(incomingNumber);
            //反注册内存观察者
            getContentResolver().unregisterContentObserver(this);
        }


    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();

        dao = new BlackNumberDao(this);
        //获取到电话的管理者

        tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);


        listener = new MyPhoneStateListener();

        //设置电话状态监听
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

        /**
         * 区别：动态注册的优先级更高
         */

        receiver = new InnerSmsReceiver();

        IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        //设置当前短信的优先级
        filter.setPriority(Integer.MAX_VALUE);

        registerReceiver(receiver, filter);
    }

    /**
     * 删除电话号码
     *
     * @param incomingNumber
     */
    public void deleteCallLog(String incomingNumber) {
        Uri uri = Uri.parse("content://call_log/calls/");
        getContentResolver().delete(uri, "number=?", new String[]{incomingNumber});

    }

    /**
     * 挂断
     */
    public void endCall() {

        try {

            //反射当前的对象
            Class<?> clazz = getClassLoader().loadClass("android.os.ServiceManager");
            //反射当前的方法
            Method method = clazz.getDeclaredMethod("getService", String.class);
            //调用方法
            IBinder iBinder = (IBinder) method.invoke(null, TELEPHONY_SERVICE);

            ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);

            iTelephony.endCall();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

    private class InnerSmsReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            System.out.println("InnerSmsReceiver接收到广播了");
            // 获取到短信
            Object[] objs = (Object[]) intent.getExtras().get("pdus");

            for (Object object : objs) {
                // 初始化一个解析对象
                SmsMessage smsMessage = SmsMessage
                        .createFromPdu((byte[]) object);
                // 获取到短信号码
                String number = smsMessage.getOriginatingAddress();

                // 获取到短信内容
                String messageBody = smsMessage.getMessageBody();

                // 判断用户的电话号码是否已经在我的仇人名单里面

                String mode = dao.findMode(number);
                /**
                 * 1 电话拦截 + 短信拦截(全部拦截) 2 电话拦截 3短信拦截
                 */
                // 如果当前的拦截模式是1或者是3的话。就需要拦截
                if ("1".equals(mode) || "3".equals(mode)) {
                    System.out.println("哈哈。你被哥拦截了");
                    abortBroadcast();
                }

            }

        }

    }

    @Override
    public void onDestroy() {
        unregisterReceiver(receiver);
        receiver = null;
        tm.listen(listener, PhoneStateListener.LISTEN_NONE);
        listener = null;
        super.onDestroy();
    }

}